package com.nit.server.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nit.server.common.*;
import com.nit.server.entity.Community;
import com.nit.server.entity.Menu;
import com.nit.server.entity.User;
import com.nit.server.service.MenuService;
import com.nit.server.service.UserService;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zb
 * @since 2023-7-16
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private MenuService menuService;
    @Autowired
    private RedisUtil redisUtil;
    private final Logger logger = LoggerFactory.getLogger(UserController.class);
    @GetMapping("/list")
    public List<User> list(){
        return  userService.list();
    }
    /**
     * @descriptions: 获取验证码
     * @author: zb
     * @date: 2023-7-16 17:36
     * @version: 1.0
     */
    @RequestMapping(path = "/kaptcha", method = RequestMethod.GET)
    public Result getKaptcha() {
//        Result result = new Result();
        try {
            KaptchaDTO kaptchaDTO = userService.getKaptcha();
            return Result.success(kaptchaDTO);
        } catch (Exception e) {
            logger.error(e.toString());
            return Result.fail();
        }
    }
    @GetMapping("/findByNo")
    public Result findByNo(@RequestParam String userNum){
        List list = userService.lambdaQuery().eq(User::getUserNum,userNum).list();
        return list.size()>0?Result.success():Result.fail();
    }
    //新增
    @PostMapping("/add")
    public Result add(@RequestBody User user){
        return userService.save(user)?Result.success():Result.fail();
    }
    //修改
    @PostMapping("/update")
    public Result update(@RequestBody User user){
        return userService.updateById(user)?Result.success():Result.fail();
    }
    //新增或修改
    @PostMapping("/addOrUpdate")
    public boolean addOrUpdate(@RequestBody User user){
        return userService.saveOrUpdate(user);
    }
    //删除
    @GetMapping("/delete")
    public Result delete(@RequestParam String userId){
        return userService.removeById(userId)?Result.success():Result.fail();
    }
    //查询(模糊，匹配)
    @PostMapping("/check")
    public Result check(@RequestBody User user){
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper();
        //判断是否为空
        if (StringUtils.isNotBlank(user.getUserName())){
            lambdaQueryWrapper.like(User::getUserName,user.getUserName());
        }
        return Result.success(userService.list(lambdaQueryWrapper));
    }
    //分页
    @PostMapping("/listPage")
//    public List<User> listPage(@RequestBody HashMap map){
    public List<User> listPage(@RequestBody QueryPageParam pageParam){
        System.out.println(pageParam);
        String userName = (String)pageParam.getParams().get("userName");
        Page<User> page = new Page<>();
        page.setCurrent(pageParam.getPageNum());
        page.setSize(pageParam.getPageSize());

        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.like(User::getUserName,userName);
//        IPage result = userService.pageC(page);
        IPage result = userService.pageCC(page,lambdaQueryWrapper);
        System.out.println("total=="+result.getTotal());
//        return userService.list(lambdaQueryWrapper);

        return result.getRecords();
    }
    @PostMapping("/listPage1")
//    public List<User> listPage(@RequestBody HashMap map){
    public Result listPage1(@RequestBody QueryPageParam pageParam){
        System.out.println(pageParam);
        String userName = (String)pageParam.getParams().get("userName");
        String roleId = (String)pageParam.getParams().get("roleId");
        String cId = (String)pageParam.getParams().get("cId");
        Page<User> page = new Page<>();
        page.setCurrent(pageParam.getPageNum());
        page.setSize(pageParam.getPageSize());
        System.out.println(cId);
        QueryWrapper<User> queryWrapper = new QueryWrapper();
        queryWrapper.apply("a.c_id = b.c_id ");
        if (StringUtils.isNotBlank(cId)){
            queryWrapper.eq("a.c_id",cId);
        }
        if (StringUtils.isNotBlank(roleId)){
            queryWrapper.eq("a.role_id",roleId);
        }
        if (StringUtils.isNotBlank(userName)){
            queryWrapper.like("a.user_name",userName);
        }
//        IPage result = userService.pageC(page);
        IPage result = userService.pageCC(page,queryWrapper);
        System.out.println("total=="+result.getTotal());
//        return userService.list(lambdaQueryWrapper);

        return Result.success(result.getTotal(), result.getRecords());
    }
    //登录
    @PostMapping("/login")
    public Result login(@RequestBody LoginDTO user){
        String uuid = user.getUuid();
        String userCode = user.getUserCode();
        if (uuid == null || redisUtil.get(uuid) == null) {
            return Result.fail(JSONObject.parseObject("{ 'info': '验证码已过期，请单击刷新' }"));
        } else if (!((String) redisUtil.get(uuid)).equalsIgnoreCase(userCode)) {
            return Result.fail(JSONObject.parseObject("{ 'info': '验证码错误' }"));
        }else {
            List list = userService.lambdaQuery().eq(User::getUserNum,user.getUserNum()).eq(User::getUserPassword,user.getUserPassword()).list();
            List list1 = userService.lambdaQuery().eq(User::getUserPhone,user.getUserNum()).eq(User::getUserPassword,user.getUserPassword()).list();
            if (list.size()>0){
                User user1 = (User) list.get(0);
                List Menulist = menuService.lambdaQuery().like(Menu::getMenuRight,user1.getRoleId()).list();
                HashMap res = new HashMap();
                res.put("user",user1);
                res.put("menu",Menulist);
                return Result.success(res);
            }else if (list1.size()>0){
                User user2 = (User) list1.get(0);
                List Menulist = menuService.lambdaQuery().like(Menu::getMenuRight,user2.getRoleId()).list();
                HashMap res = new HashMap();
                res.put("user",user2);
                res.put("menu",Menulist);
                return Result.success(res);
            }
            return Result.fail(JSONObject.parseObject("{ 'info': '用户名或密码错误' }"));
        }
    }
    //检查该社团是否有管理员
    @GetMapping("/checkadmin")
    public Result checkadmin(@RequestParam String cId){
        List list = userService.lambdaQuery().eq(User::getCId,cId).eq(User::getRoleId,'1').list();

        if (list.size()>0){
            return Result.success();
        }
        return Result.fail();
    }
}
